// src/composables/useUpgradeProcess.ts
import { ref, computed, onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUpgradeStore, UpgradeStatus } from "@/store";
import type {
  ProgramInfo,
  StartUpgradeResponse,
  StartRollbackResponse,
  BackupResponse,
} from "@/api/hmi/upgrade.api";
import { FileInfo } from "@/api/file.api";
import { storeToRefs } from "pinia";
import type { TableInstance } from "element-plus";

/**
 * 升级页面业务逻辑Composable
 */
export function useUpgradeProcess() {
  const upgradeStore = useUpgradeStore();

  // 使用 storeToRefs 来解构状态属性，它们将保持 ref 形式
  const { currentProgramInfo, newProgramInfo, backupList, progressDisplay, upgradeCurrentStatus } =
    storeToRefs(upgradeStore);

  // 从 Store 中解构状态和操作
  const {
    setNewProgramInfo,
    startUpgradeProcess,
    startRollbackProcess,
    resetUpgradeState,
    stopPollingProgress,
    backupHandle,
    fetchBackupList,
    setSelectedBackup,
  } = upgradeStore;

  // 本地状态变量
  const selectedBackup = ref<string | null>(null);
  const backupTableRef = ref<TableInstance | null>(null);
  const newFileList = ref<FileInfo[]>([]);
  const backupFileList = ref<FileInfo[]>([]);
  const backupInfo = ref<any>(null);

  // const newInfo = ref<ProgramInfo | null>(null);

  // 辅助判断操作是否进行中
  const isOperationInProgress = computed(() => {
    return (
      upgradeCurrentStatus.value === UpgradeStatus.UPGRADING ||
      upgradeCurrentStatus.value === UpgradeStatus.ROLLING_BACK ||
      upgradeCurrentStatus.value === UpgradeStatus.UPLOADING
    ); // 如果文件上传也算阻塞操作
  });

  // 判断是否可以点击“开始升级”按钮
  const canStartUpgrade = computed(() => {
    return newProgramInfo.value !== null && !isOperationInProgress.value;
  });

  // 判断是否可以点击“开始回滚”按钮
  const canStartRollback = computed(() => {
    // 回滚通常不依赖于新文件，但要确保没有其他操作进行中
    return !isOperationInProgress.value;
  });

  /**
   * 文件上传成功后的回调
   * 模拟从文件上传组件获取到新程序信息
   * @param fileInfo 模拟的文件信息
   */
  const handleFileUploaded = (fileInfo: {
    name: string;
    version: string;
    crc: string;
    size: number;
  }) => {
    const newInfo: ProgramInfo = {
      name: fileInfo.name,
      version: fileInfo.version,
      uploadTime: new Date().toLocaleString(), // 模拟上传时间
      crc: fileInfo.crc,
      path: "",
    };
    setNewProgramInfo(newInfo);
    // 文件上传成功后，如果之前有失败或成功状态，可以考虑重置进度条
    if (
      upgradeCurrentStatus.value === UpgradeStatus.SUCCESS ||
      upgradeCurrentStatus.value === UpgradeStatus.FAIL
    ) {
      upgradeStore.updateUpgradeProgress(0, "文件已上传，等待操作", UpgradeStatus.IDLE);
    }
    ElMessage.success(`文件 ${fileInfo.name} 上传成功，版本：${fileInfo.version}`);
  };

  /**
   * 文件上传成功，本地模拟文件信息
   *
   */
  const handleFileUploaded2 = (val: FileInfo[]) => {
    console.log("handleFileUploaded2 文件上传成功，本地模拟文件信息", val);
    if (val.length > 0) {
      const fileInfo = val[0];
      const [name, version, crc] = fileInfo.path.replace(".tar.gz", "").split("_");
      const newInfo: ProgramInfo = {
        name: name,
        version: version,
        uploadTime: new Date().toLocaleString(), // 模拟上传时间
        crc: crc,
        path: fileInfo.path,
      };
      setNewProgramInfo(newInfo);
    } else {
      setNewProgramInfo(null);
    }
  };

  /**
   * 处理"开始升级"按钮点击
   */
  const onStartUpgrade = async (): Promise<void> => {
    if (!canStartUpgrade.value) {
      if (!newProgramInfo.value) {
        ElMessage.warning("请先上传新程序文件！");
      } else {
        ElMessage.warning("当前已有操作正在进行中，请稍后再试！");
      }
      return;
    }

    try {
      const result = await startUpgradeProcess();
      if (!result) {
        console.warn("升级启动失败");
      }
    } catch (error: any) {
      console.error("onStartUpgrade error:", error);
      ElMessage.error("升级操作异常！");
    } finally {
      // 无论成功或失败，都刷新备份点列表
      try {
        await fetchBackupList();
      } catch (error: any) {
        console.error("fetchBackupList in onStartUpgrade error:", error);
        ElMessage.error("获取备份点列表失败！");
      }
    }
  };

  /**
   * 处理"开始回滚"按钮点击
   */
  const onStartRollback = async (): Promise<void> => {
    if (!canStartRollback.value) {
      ElMessage.warning("当前已有操作正在进行中，请稍后再试！");
      return;
    }

    try {
      const result = await startRollbackProcess();
      if (result) {
        newFileList.value = [];
      }
    } catch (error: any) {
      console.error("onStartRollback error:", error);
      ElMessage.error("回滚操作异常！");
    }
  };

  /**
   * 备份文件上传成功后的回调
   * @param val 文件信息列表
   */
  const handleBackupFileUploaded = (val: FileInfo[]): void => {
    backupFileList.value = val;
    if (val.length > 0) {
      backupInfo.value = val[0];
    } else {
      backupInfo.value = null;
    }
  };

  /**
   * 备份按钮点击事件
   */
  const handleBackup = async (): Promise<void> => {
    if (backupInfo.value) {
      try {
        const result = await backupHandle(backupInfo.value.path);
        if (result) {
          ElMessage.success("备份成功！");
        }
      } catch (error: any) {
        console.error("handleBackup error:", error);
        ElMessage.error("备份操作异常！");
      }
      // 备份成功后刷新备份列表
      try {
        await fetchBackupList();
      } catch (error: any) {
        console.error("fetchBackupList on mounted error:", error);
        ElMessage.error("获取备份点列表失败！");
      }
    } else {
      ElMessage.warning("请先上传备份文件！");
    }
  };

  /**
   * 清除新程序文件信息
   */
  const clearNewProgram = () => {
    setNewProgramInfo(null);
    ElMessage.info("新程序文件信息已清除。");
    // 清除后重置状态
    upgradeStore.updateUpgradeProgress(0, "等待操作...", UpgradeStatus.IDLE);
    stopPollingProgress(); // 确保停止轮询
  };

  // 组件挂载时
  onMounted(async () => {
    try {
      await fetchBackupList();
    } catch (error: any) {
      console.error("fetchBackupList on mounted error:", error);
      ElMessage.error("获取备份点列表失败！");
    }
  });

  // 组件卸载时，执行清理工作
  onUnmounted(() => {
    resetUpgradeState(); // 清理Pinia状态和停止轮询
  });

  // 处理表格选择变化，确保只选择一行
  const handleSelectionChange = (selection: any[]) => {
    if (selection.length > 1) {
      // 如果选择了多行，只保留最后一行
      const lastSelected = selection[selection.length - 1];
      if (backupTableRef.value) {
        // 清除所有选择
        backupTableRef.value.clearSelection();
        // 选择最后一行
        backupTableRef.value.toggleRowSelection(lastSelected, true);
        selectedBackup.value = lastSelected.backupName;
        setSelectedBackup(lastSelected.backupName);
      }
    } else if (selection.length === 1) {
      // 只选择一行
      selectedBackup.value = selection[0].backupName;
      setSelectedBackup(selection[0].backupName);
    } else {
      // 没有选择任何行
      selectedBackup.value = null;
      setSelectedBackup(null);
    }
  };

  // 处理回滚操作
  const handleRollback = async (): Promise<void> => {
    if (!selectedBackup.value) {
      ElMessage.warning("请先选择一个备份点！");
      return;
    }

    try {
      await ElMessageBox.confirm(
        `确定要回滚到备份点 "${selectedBackup.value}" 吗？此操作不可逆。`,
        "确认回滚",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      );

      const result = await startRollbackProcess(selectedBackup.value);
      if (result) {
        ElMessage.success(result.message || "回滚任务已成功启动！");
      }
    } catch (error: any) {
      if (error === "cancel") {
        return;
      }
      console.error("handleRollback error:", error);
      ElMessage.error("回滚操作异常！");
    }
  };

  return {
    newFileList,
    backupFileList,
    currentProgramInfo,
    backupInfo,
    newProgramInfo,
    backupList, // 暴露 backupList
    selectedBackup, // 暴露 selectedBackup
    backupTableRef, // 暴露 backupTableRef
    progressDisplay,
    upgradeCurrentStatus,
    isOperationInProgress,
    canStartUpgrade,
    canStartRollback,
    handleFileUploaded,
    handleFileUploaded2, // 模拟资源文件上传成功后的回调
    handleBackupFileUploaded,
    handleBackup,
    fetchBackupList, // 暴露 fetchBackupList 方法
    handleSelectionChange, // 暴露 handleSelectionChange 方法
    handleRollback, // 暴露 handleRollback 方法
    onStartUpgrade,
    onStartRollback,
    clearNewProgram,
  };
}
